import { PaginationProps } from "ant-design-vue/es/pagination";
import { debounce } from "lodash-es";
import { Ref, reactive, watch } from "vue";

export const useTableData = (
  requestMethod: (
    params: any
  ) => Promise<{ total: number; list: Record<string, any>[] }>,
  filterData: Ref<Record<string, any>>
) => {
  const tableProps = reactive<{
    rowKey?: string;
    pagination: false | PaginationProps;
    dataSource: Record<string, any>[];
    columns?: ColumnItem[];
    defaultExpandAllRows?: boolean;
    rowSelection?: any;
    loading?: boolean;
  }>({
    rowKey: "id",
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showTotal: (total) => `共 ${total} 条`,
    },
    dataSource: [],
    columns: [],
  });
  async function getData(isInit?: boolean) {
    try {
      if (isInit && tableProps.pagination) {
        tableProps.pagination.current = 1;
      }
      tableProps.loading = true;
      const { current, pageSize } = tableProps.pagination || {};
      await requestMethod({ current, pageSize, ...filterData.value }).then(
        (res: { total: number; list: Record<string, any>[] }) => {
          const { total, list } = res;
          tableProps.dataSource = list;
          if (tableProps.pagination) tableProps.pagination.total = total;
        }
      );
    } catch (e) {
      console.warn(e);
    } finally {
      tableProps.loading = false;
    }
  }
  const getDataDebounce = debounce(getData, 500);
  watch(
    filterData,
    () => {
      getDataDebounce();
    },
    { deep: true }
  );
  getData(true);

  const handleTableChange = (pageConfig: PaginationProps) => {
    Object.assign(tableProps.pagination, pageConfig);
    getDataDebounce();
  };
  return { tableProps, handleTableChange, getData };
};
// export const useList = (
//   requestMethod: (
//     params: any
//   ) => Promise<{ total: number; list: Record<string, any>[] }>,
//   filterData: Ref<Record<string, any>>
// ) => {

//   return { tableProps, handleTableChange };
// };
